package com.jiawa.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.Req.TrainCarriageSaveReq;
import com.jiawa.train.business.domain.Req.TrainStationQueryReq;
import com.jiawa.train.business.domain.TrainCarriage;
import com.jiawa.train.business.domain.TrainCarriageExample;
import com.jiawa.train.business.domain.resp.TrainCarriageQueryResp;
import com.jiawa.train.business.enums.SeatColEnum;
import com.jiawa.train.business.mapper.TrainCarriageMapper;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TrainCarriageService {

    @Autowired
    private TrainCarriageMapper trainCarriageMapper;

    public PageResp<TrainCarriageQueryResp> queryList( TrainStationQueryReq req) {
        TrainCarriageExample example = new TrainCarriageExample();
        PageHelper.startPage(req.getPage(), req.getSize());
        List<TrainCarriage> list = trainCarriageMapper.selectByExample(example);
        List<TrainCarriageQueryResp> respList = BeanUtil.copyToList(list, TrainCarriageQueryResp.class);
        PageInfo pageInfo = new PageInfo(list);

        PageResp<TrainCarriageQueryResp> resp = new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setList(respList);
        return resp;
    }

    public void save( TrainCarriageSaveReq req) {
        TrainCarriage carriage = new TrainCarriage();
        // 自动计算出列数和总座位数
        List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType());
        req.setColCount(seatColEnums.size());
        req.setSeatCount(req.getColCount() * req.getRowCount());

        BeanUtil.copyProperties(req, carriage);
        if(ObjectUtil.isNull(carriage.getId())) {
            carriage.setId(SnowUtil.getSnowflakeNextId());
            carriage.setCreateTime(new Date());
            carriage.setUpdateTime(new Date());
            trainCarriageMapper.insert(carriage);
        }else {
            carriage.setUpdateTime(new Date());
            trainCarriageMapper.updateByPrimaryKeySelective(carriage);
        }
    }

    public void delete(Long id) {
        trainCarriageMapper.deleteByPrimaryKey(id);
    }

    public List<TrainCarriage> selectByTrainCode(String trainCode) {
        TrainCarriageExample trainCarriageExample = new TrainCarriageExample();
        trainCarriageExample.setOrderByClause("`index` asc");
        TrainCarriageExample.Criteria criteria = trainCarriageExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode);
        return trainCarriageMapper.selectByExample(trainCarriageExample);

    }
}
